package org.mango.springboot.base;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by meigang on 17/9/9.
 */
public class BaseController {

    @Resource
    HttpServletRequest req;

    protected String getCtx(){
        return req.getContextPath();
    }

    protected void setAttr(String key,Object value){
        req.setAttribute(key,value);
    }

    protected Object getAttr(String key){
        return req.getAttribute(key);
    }

    protected void setSessionAttr(String key,Object value){
        req.getSession().setAttribute(key,value);
    }

    protected Object getSessionAttr(String key){
        return req.getSession().getAttribute(key);
    }


    protected String ajaxJson(int state){
        JSONObject json = new JSONObject();
        json.put("state",state);
        return json.toJSONString();
    }

    protected String ajaxJson(int state,Object msg){
        JSONObject json = new JSONObject();
        json.put("state",state);
        json.put("msg",msg);
        return json.toJSONString();
    }

    protected String ajaxJson(int state,String msg){
        JSONObject json = new JSONObject();
        json.put("state",state);
        json.put("msg",msg);
        return json.toJSONString();
    }

    protected String getJarReactStr(ResourcePatternResolver resolver, String m, String module_path) throws IOException {
        InputStream is = resolver.getResource(module_path+m).getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[bis.available()];
        bis.read(buffer);
        String packageStr = new String(buffer,"utf-8");
        bis.close();
        is.close();
        return packageStr;
    }

    protected void renderString(HttpServletResponse res,String str) throws IOException {
        res.setCharacterEncoding("utf-8");
        res.getOutputStream().write(str.getBytes("utf-8"));
        res.getOutputStream().close();
    }

    protected void renderJson(HttpServletResponse res,JSONObject json) throws IOException {
        res.setCharacterEncoding("utf-8");
        res.getOutputStream().write(json.toJSONString().getBytes("utf-8"));
        res.getOutputStream().close();
    }
}
